package fun.tan90.easy.binlog.plugin.mysql.listener;


import cn.hutool.db.Db;
import cn.hutool.db.DbUtil;
import cn.hutool.db.Entity;
import cn.hutool.json.JSONObject;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.zaxxer.hikari.HikariDataSource;
import fun.tan90.easy.binlog.base.constants.EventTypeConstants;
import fun.tan90.easy.binlog.base.enums.OutputResEnum;
import fun.tan90.easy.binlog.base.enums.OutputTypeEnum;
import fun.tan90.easy.binlog.plugin.common.constants.DamiEventConstants;
import fun.tan90.easy.binlog.plugin.common.event.BinlogDataEvent;
import fun.tan90.easy.binlog.plugin.common.event.BinlogDataEventRes;
import fun.tan90.easy.binlog.plugin.common.listener.BinlogEventPluginListener;
import fun.tan90.easy.binlog.plugin.common.model.BinlogData;
import fun.tan90.easy.binlog.plugin.common.model.BinlogOutputRule;
import fun.tan90.easy.binlog.plugin.common.model.TableMeta;
import lombok.extern.slf4j.Slf4j;
import org.noear.dami.Dami;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.util.CollectionUtils;

import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * description 应用初始化后置处理器，防止 spring 事件被多次执行
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2022/8/17 8:31
 */
@Slf4j
public class MysqlEventProcessor implements BinlogEventPluginListener, ApplicationListener<ApplicationReadyEvent> {

    private final AtomicBoolean initialized = new AtomicBoolean(false);

    private final LoadingCache<String, HikariDataSource> mysqlClientCache;

    public MysqlEventProcessor(LoadingCache<String, HikariDataSource> mysqlClientCache) {
        this.mysqlClientCache = mysqlClientCache;
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        if (initialized.compareAndSet(false, true)) {
            Dami.<BinlogDataEvent, BinlogDataEventRes>bus().listen(DamiEventConstants.BINLOG_EVENT_TOPIC + outputType(), payload -> {
                BinlogDataEvent binlogDataEvent = payload.getContent();
                String eventType = binlogDataEvent.getEventType();
                List<BinlogData> binlogDataList = binlogDataEvent.getBinlogDataList();
                TableMeta tableMeta = binlogDataEvent.getTableMeta();
                List<String> prNames = tableMeta.getPrNames();
                List<String> columnNames = tableMeta.getColumnNames();
                List<BinlogOutputRule> binlogOutputTypeRules = binlogDataEvent.getBinlogOutputRules();
                for (BinlogOutputRule binlogOutputRule : binlogOutputTypeRules) {
                    String outputRuleCountId = binlogOutputRule.getOutputRuleCountId();
                    String outputCode = binlogOutputRule.getOutputCode();
                    HikariDataSource hikariDataSource = mysqlClientCache.get(outputCode);
                    if (hikariDataSource != null) {
                        Db db = DbUtil.use(hikariDataSource);
                        for (BinlogData binlogData : binlogDataList) {
                            if (filterOutput(binlogOutputRule, binlogData)) {
                                String table = binlogData.getTable();
                                if (EventTypeConstants.WRITE.equals(eventType)) {
                                    Entity entity = Entity.create(table);
                                    JSONObject data = binlogData.getData();
                                    for (String columnName : columnNames) {
                                        entity.set(columnName, data.get(columnName));
                                    }
                                    try {
                                        db.insert(entity);
                                        reply(payload, outputRuleCountId, OutputResEnum.SUCCESS);
                                    } catch (SQLException e) {
                                        reply(payload, outputRuleCountId, OutputResEnum.ERROR);
                                        log.error("数据写入失败 {}", e.getMessage());
                                    }
                                } else {
                                    JSONObject data = binlogData.getData();
                                    if (!CollectionUtils.isEmpty(prNames)) {
                                        Entity where = Entity.create(table);
                                        for (String prName : prNames) {
                                            where.set(prName, data.get(prName));
                                        }
                                        if (EventTypeConstants.UPDATE.equals(eventType)) {
                                            List<String> diffCols = binlogData.getDiffCols();
                                            Entity entity = Entity.create(table);
                                            for (String colName : diffCols) {
                                                entity.set(colName, data.get(colName));
                                            }
                                            try {
                                                db.update(entity, where);
                                                reply(payload, outputRuleCountId, OutputResEnum.SUCCESS);
                                            } catch (SQLException e) {
                                                reply(payload, outputRuleCountId, OutputResEnum.ERROR);
                                                log.error("数据更新失败 {}", e.getMessage());
                                            }
                                        } else {
                                            try {
                                                db.del(where);
                                                reply(payload, outputRuleCountId, OutputResEnum.SUCCESS);
                                            } catch (SQLException e) {
                                                reply(payload, outputRuleCountId, OutputResEnum.ERROR);
                                                log.error("数据删除失败 {}", e.getMessage());
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            });
        }
    }

    @Override
    public String outputType() {
        return OutputTypeEnum.MYSQL.getOutput();
    }
}
